<template>
  <div class="main-layout">
    <div class="main-content chat-room-card">
      <!-- 顶部栏：显示对方信息 -->
      <div class="chat-header">
        <button class="chat-back-btn" @click="goBack">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="22"
            height="22"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <line x1="19" y1="12" x2="5" y2="12"></line>
            <polyline points="12 19 5 12 12 5"></polyline>
          </svg>
          返回
        </button>
        <router-link
          v-if="targetUser && targetUser.id"
          :to="{
            name: 'user-profile',
            params: { id: targetUser.id },
            query: { nickname: targetUser.nickname },
          }"
          class="chat-nickname"
        >
          {{ targetUser.nickname || '加载中...' }}
        </router-link>
        <span v-else class="chat-nickname">加载中...</span>
      </div>

      <!-- 消息列表区域 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="!targetUser" class="error-msg">用户信息加载失败</div>
        <template v-else>
          <div v-if="messages.length === 0" class="empty-messages">👋 来和Ta打个招呼吧~</div>
          <div v-else class="message-list">
            <div v-for="msg in messages" :key="msg.messageId">
              <div class="msg-time">{{ formatMsgTime(msg.createTime) }}</div>
              <div class="message-item" :class="{ 'message-self': msg.senderId === currentUserId }">
                <router-link
                  :to="{
                    name: 'user-profile',
                    params: { id: msg.senderId },
                    query: { nickname: msg.senderNickname },
                  }"
                  class="avatar-link"
                >
                  <img
                    :src="getUserAvatar(msg.senderPhoto, msg.senderId)"
                    :alt="msg.senderNickname + '的头像'"
                    class="avatar"
                  />
                </router-link>
                <div class="message-content">
                  {{ msg.content }}
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>

      <!-- 底部输入区域 -->
      <div class="input-area">
        <textarea
          v-model="newMessage"
          placeholder="输入消息..."
          @keypress.enter.prevent="sendMessage"
          :disabled="!wsConnected"
        ></textarea>
        <button @click="sendMessage" :disabled="!wsConnected || !newMessage.trim()">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount, nextTick, computed, watchEffect, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { getUserAvatar } from '@/utils/avatar'
import api from '@/services/api'

const route = useRoute()
const router = useRouter()
console.log('[ChatRoomView] route.params:', route.params)
const authStore = useAuthStore()
const currentUserId = computed(() => authStore.user?.id)

// 状态管理
const loading = ref(true)
let initialized = false
const messages = ref([])
const newMessage = ref('')
const targetUser = ref({})
const wsConnected = ref(false)
const messagesContainer = ref(null)
let ws = null
let firstLoad = true

// WebSocket连接管理
function connectWebSocket() {
  if (!currentUserId.value) return
  ws = new WebSocket(`ws://localhost:8081/chat/${currentUserId.value}`)
  ws.onopen = () => {
    console.log('WebSocket连接已建立')
    wsConnected.value = true
  }
  ws.onmessage = (event) => {
    const msg = JSON.parse(event.data)
    if (!msg.senderNickname) {
      if (msg.senderId === currentUserId.value) {
        msg.senderNickname = authStore.user?.nickname
      } else if (msg.senderId === targetUser.value.id) {
        msg.senderNickname = targetUser.value.nickname
      }
    }
    const isSelf = msg.senderId === currentUserId.value
    if (isSelf) {
      console.log('[WebSocket] 已收到自己发出的消息（发送成功）:', msg)
    } else {
      console.log('[WebSocket] 收到对方消息:', msg)
    }
    if (
      (msg.senderId === targetUser.value.id || msg.receiverId === targetUser.value.id) &&
      !messages.value.some((m) => m.messageId === msg.messageId)
    ) {
      messages.value.push(msg)
      scrollToBottom()
    }
  }
  ws.onclose = () => {
    console.log('WebSocket连接已关闭')
    wsConnected.value = false
  }
}

// 发送消息
async function sendMessage() {
  if (!newMessage.value.trim() || !wsConnected.value) return
  const messageData = {
    receiverId: targetUser.value.id,
    content: newMessage.value.trim(),
    messageType: 'TEXT',
  }
  console.log('[sendMessage] 请求发送消息:', messageData)
  ws.send(JSON.stringify(messageData))

  // 主动渲染本地消息
  const now = new Date()
  messages.value.push({
    messageId: Date.now(), // 临时ID
    senderId: currentUserId.value,
    receiverId: targetUser.value.id,
    content: messageData.content,
    createTime: now.toISOString(),
    isDelivered: false, // 可根据需要调整
    messageType: messageData.messageType,
    senderPhoto: authStore.user?.photo,
    senderNickname: authStore.user?.nickname,
  })
  newMessage.value = ''
  scrollToBottom()
}

// 滚动到底部
async function scrollToBottom() {
  await nextTick()
  if (messagesContainer.value) {
    const el = messagesContainer.value
    el.scrollTop = el.scrollHeight
    console.log(
      '[ChatRoomView] scrollToBottom执行',
      'scrollTop:',
      el.scrollTop,
      'scrollHeight:',
      el.scrollHeight,
      'clientHeight:',
      el.clientHeight,
      'messages.length:',
      messages.value.length,
      'lastMsg:',
      messages.value[messages.value.length - 1],
      'container:',
      el.outerHTML.slice(0, 200) + '...',
    )
  } else {
    console.log('[ChatRoomView] scrollToBottom未执行，messagesContainer不存在')
  }
}

// 加载历史消息
async function loadHistoryMessages() {
  try {
    console.log(
      '[ChatRoomView] 加载历史消息，senderId:',
      currentUserId.value,
      'receiverId:',
      targetUser.value.id,
    )
    const res = await api.historyMessage({
      senderId: currentUserId.value,
      receiverId: targetUser.value.id,
    })
    console.log('[ChatRoomView] historyMessage返回:', res)
    if (res.data?.code === 0 && Array.isArray(res.data.data)) {
      messages.value = res.data.data.map((msg) => {
        if (!msg.senderNickname) {
          if (msg.senderId === currentUserId.value) {
            msg.senderNickname = authStore.user?.nickname
          } else if (msg.senderId === targetUser.value.id) {
            msg.senderNickname = targetUser.value.nickname
          }
        }
        return msg
      })
      await nextTick()
      console.log('[ChatRoomView] nextTick后准备滚动，messages.length:', messages.value.length)
      scrollToBottom()
    } else {
      console.error('[ChatRoomView] 获取历史消息失败:', res.data)
    }
  } catch (error) {
    console.error('[ChatRoomView] 加载历史消息失败:', error)
  }
}

// 加载目标用户信息
async function loadTargetUserInfo() {
  try {
    console.log('[ChatRoomView] 加载目标用户信息，nickname:', route.query.nickname)
    const res = await api.getOtherInfo({ nickname: route.query.nickname })
    console.log('[ChatRoomView] getOtherInfo返回:', res)
    if (res.data?.code === 0) {
      targetUser.value = res.data.data
    } else {
      targetUser.value = null
      console.error('[ChatRoomView] 获取用户信息失败:', res.data)
    }
  } catch (error) {
    targetUser.value = null
    console.error('[ChatRoomView] 加载用户信息失败:', error)
  }
}

// 聊天页面初始化逻辑，只有在 currentUserId 有值时才执行
watchEffect(async () => {
  if (!currentUserId.value || initialized) return
  loading.value = true
  initialized = true
  console.log('[ChatRoomView] watchEffect触发，currentUserId:', currentUserId.value)
  try {
    await loadTargetUserInfo()
    await loadHistoryMessages()
    await scrollToBottom() // 保证初次进入后滚动到底部
    connectWebSocket()
  } catch (e) {
    console.error('[ChatRoomView] 初始化异常:', e)
  } finally {
    loading.value = false
    console.log('[ChatRoomView] 初始化结束，loading:', loading.value)
  }
})

watch(
  () => messages.value.length,
  async (newLen) => {
    if (firstLoad && newLen > 0) {
      await nextTick()
      scrollToBottom()
      firstLoad = false
      console.log('[ChatRoomView] watch: 首次加载消息后自动滚动')
    }
  },
)

watch(
  () => loading.value,
  async (val) => {
    if (val === false && messages.value.length > 0) {
      await nextTick()
      scrollToBottom()
      console.log('[ChatRoomView] watch: loading结束后自动滚动')
    }
  },
)

onBeforeUnmount(() => {
  if (ws) {
    ws.close()
  }
})

function formatMsgTime(timeStr) {
  const date = new Date(timeStr)
  const now = new Date()
  const pad = (n) => n.toString().padStart(2, '0')
  // 获取当天0点
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const msgDay = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  const diff = (today - msgDay) / (1000 * 60 * 60 * 24)
  if (date.getFullYear() !== now.getFullYear()) {
    // 跨年
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
  } else if (diff === 1) {
    // 昨天
    return `昨天 ${pad(date.getHours())}:${pad(date.getMinutes())}`
  } else if (diff === 0) {
    // 今天
    return `${pad(date.getHours())}:${pad(date.getMinutes())}`
  } else {
    // 今年内
    return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
  }
}

function goBack() {
  if (window.history.length > 1) {
    window.history.back()
  } else {
    router.push('/chat')
  }
}
</script>

<style scoped>
.main-layout {
  min-height: 100vh;
  background: var(--color-bg);
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.chat-room-card.main-content {
  flex: 1 1 0;
  width: calc(90vw - 32px); /* 16px 左右外边距 */
  max-width: 100vw;
  margin: 16px auto;
  background: var(--color-input-bg);
  border-radius: 0.5rem;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  min-height: calc(90vh - 32px - 56px); /* 32px外边距+56px导航栏 */
  max-height: calc(90vh - 32px - 56px);
  box-sizing: border-box;
  min-height: 0; /* 关键：允许子元素收缩 */
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem 1rem 2rem;
  background: var(--color-surface);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1;
  border-top-left-radius: 0.5rem;
  border-top-right-radius: 0.5rem;
}

.chat-back-btn {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  background: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: 0.4rem;
  padding: 0.4rem 0.9rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition:
    background 0.2s,
    color 0.2s;
}
.chat-back-btn:hover {
  background: var(--color-surface-hover);
  color: var(--color-primary);
}

.chat-nickname {
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--color-primary);
  cursor: pointer;
  transition: color 0.2s;
  text-decoration: none;
}
.chat-nickname:hover {
  color: var(--color-primary-hover);
}

.messages-container {
  flex: 1 1 0;
  min-height: 0; /* 关键：允许自身收缩，出现滚动条 */
  overflow-y: auto;
  padding: 1rem 2rem;
  display: flex;
  flex-direction: column;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message-list > div {
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 0.8rem;
  max-width: 80%;
}

.message-self {
  flex-direction: row-reverse;
  align-self: flex-end;
}

.avatar-link {
  text-decoration: none;
}

.avatar {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 0.8rem;
  object-fit: cover;
  border: 2px solid var(--color-primary);
  transition: box-shadow 0.2s;
}

.avatar:hover {
  box-shadow: 0 0 0 3px var(--color-primary-focus-ring);
}

.message-content {
  padding: 0.8rem 1rem;
  border-radius: 1rem;
  max-width: 100%;
  word-break: break-word;
  font-size: 1rem;
  line-height: 1.4;
}

/* 对方消息样式 */
.message-item:not(.message-self) .message-content {
  background: var(--color-surface-alt, var(--color-surface));
  color: var(--color-text);
  border-top-left-radius: 0.2rem;
  border: 1px solid var(--color-border);
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
}

/* 自己消息样式 */
.message-self .message-content {
  background: var(--color-primary);
  color: var(--color-button-text);
  border-top-right-radius: 0.2rem;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
}

.input-area {
  padding: 1rem 2rem;
  background: var(--color-surface);
  border-top: 1px solid var(--color-border);
  display: flex;
  gap: 1rem;
  border-bottom-left-radius: 0.5rem;
  border-bottom-right-radius: 0.5rem;
}

.input-area textarea {
  flex: 1;
  min-height: 2.5rem;
  max-height: 8rem;
  padding: 0.7rem 1rem;
  border: 1px solid var(--color-border-input);
  border-radius: 0.5rem;
  resize: vertical;
  font-size: 1rem;
  background: var(--color-input-bg);
  color: var(--color-text);
}

.input-area textarea:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-focus-ring);
}

.input-area button {
  padding: 0 1.5rem;
  height: 2.5rem;
  background: var(--color-primary);
  color: var(--color-button-text);
  border: none;
  border-radius: 0.5rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.input-area button:hover:not(:disabled) {
  background: var(--color-primary-hover);
}

.input-area button:disabled {
  background: var(--color-button-disabled-bg);
  color: var(--color-button-disabled-text);
  cursor: not-allowed;
}

.loading,
.empty-messages {
  text-align: center;
  color: var(--color-text-secondary);
  margin: 2rem 0;
}
.error-msg {
  color: #e74c3c;
  font-size: 1.1rem;
  text-align: center;
  margin: 2rem 0;
}

.msg-time {
  align-self: center;
  width: auto;
  text-align: center;
  color: var(--color-primary);
  font-size: 0.95rem;
  margin-bottom: 0.2rem;
  margin-top: 0.5rem;
  letter-spacing: 1px;
  user-select: none;
}
</style>
